package com.heima.Server.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.Mapper.ArticleContentMapper;
import com.heima.Mapper.ArticleMapper;


import com.heima.file.service.FileStorageService;
import com.heima.model.Article.Pojo.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ArticleFreemaker implements com.heima.Server.ArticleFreemaker {

    private static String path = ".\\src\\main\\resources\\ArticleHTML\\";
    //    已经写好的minio相关功能的Service接口
    @Autowired
    FileStorageService fileStorageService;
    //    freemaker
    @Autowired
    Configuration configuration;
    //    查看文章详情mapper
    @Autowired
    ArticleContentMapper articleContentMapper;
    //    文章基本信息mapper
    @Autowired
    ArticleMapper articleMapper;

    //    获取具体文章
    @Override
    public boolean GetStaticArtcle(long articleid) {
//        查询文章内容
        QueryWrapper<ApArticleContent> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleid);
        ApArticleContent apArticle = articleContentMapper.selectOne(wrapper);
//        生成静态页面
        try {
            Template template = configuration.getTemplate("article.ftl");
//            数据模板
//            用list还是map装数据主要是看ftl文件里是怎么写的
            Map<String,Object> content = new HashMap<>();
            content.put("content",JSONArray.parseArray(apArticle.getContent()));
            FileWriter writer = new FileWriter
                    (path + articleid + ".html");
            template.process(content, writer);
//            把freemaker生成的html上传到minio
//            因为有图片，所以用字节流
            FileInputStream inputStream = new FileInputStream(path + articleid + ".html");
            String miniopath = fileStorageService.uploadHtmlFile(path,
                    articleid + ".html", inputStream);
//            关流
            inputStream.close();
            writer.close();
//            添加文章路径
            log.info(miniopath);
            articleMapper.updateStaticUrl(articleid, miniopath);
//            删除本地文件
            File file=new File(path+ articleid + ".html");
            file.delete();
            return true;
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
    }
}
